<?php

require_once APPPATH . 'libraries/TorrentParser/Abstract.php';

/**
 * Класс парсинга kinoarena.tv
 *
 * @author Gennadiy Kozlenko
 */
class TorrentParser_Kinoarena extends TorrentParser_Abstract {

    /**
     * Videos per page
     * @var int
     */
    const PER_PAGE = 25;
     
    /**
     * Ссылки для получения видео
     *
     * @var string
     */
    private $urls = array(
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=13&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=22&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=31&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=14&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=15&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=24&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=32&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=16&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=46&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=17&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=25&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=33&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=26&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=34&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=43&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=19&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=28&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=35&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=44&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=20&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=37&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=30&order=3&by=2&pages=[PAGE]',
        'http://kinoarena.tv/index.php?page=torrents&active=1&category=45&order=3&by=2&pages=[PAGE]',
    );
     
    /**
     * Парсинг видео и получение массива объектов TorrentEntry
     *
     * @return array
     */
    public function parseItems() {
        $entries = array();
        // Проходимся по всем урлам
        foreach ($this->urls as $url) {
            // Получаем контент
            $url = str_replace('[PAGE]', $this->page, $url);
            $content = $this->getContent($url);
            if (!empty($content)) {
                $content = str_replace(array('&nbsp;', '&amp;'), array(' ', '&'), $content);
                $match = array();
                if (preg_match('~<table\s+width="100%"\s+class="lista">(.*?)<div\s+id="footer"~msi', $content, $match)) {
                    $content = $match[1];
                    // Парсим контент
                    if (preg_match_all('~<tr[^>]*>(.*?)</tr>~msi', $content, $match)) {
                        $items = $match[1];
                        // Начинаем парсить torrent файлы
                        foreach ($items as $item) {
                            $id = '';
                            $title = '';
                            if (preg_match('~<a\s+href="index\.php\?page=torrent-details&id=([^"]+)"[^>]*>(.*?)</a>~msi', $item, $match)) {
                                $id = $match[1];
                                $title = trim($match[2]);
                            }
                            $link = 'http://kinoarena.tv/index.php?page=torrent-details&id=' . $id;
                            $torrent = 'http://kinoarena.tv/download.php?id=' . $id . '&f=video.torrent';
                            if (!empty($id) && !empty($link) && !empty($torrent) && !empty($title)) {
                                $entry = new TorrentEntry();
                                $entry->videoEntry = new VideoEntry();
                                $entry->setLink($link);
                                $entry->setTorrent($torrent);
                                $entry->setTitle($title);
                                array_push($entries, $entry);
                            }
                        }
                    }
                }
            }
            $this->obj->sleep(1, 3);
        }
        return $entries;
    }
     
    /**
     * Парсинг страницы с информацией по видео
     *
     * @param TorrentEntry $entry
     * @return TorrentEntry|bool
     */
    public function parseItem(TorrentEntry $entry) {
        // Получаем контент
        $content = $this->getContent($entry->getLink());
        if (!empty($content)) {
            $match = array();
            $size = '';
            if (preg_match('~<td[^>]*>\s*Объем\s*</td>\s*<td[^>]*>([^<]+)</td>~msi', "$content", $match)) {
                $size = $match[1];
            }
            if (!empty($size)) {
                $entry->setSize($size);
            }
            if (preg_match('~<td\s+class="lista"[^>]*>\s*(<img\s+class="linked-image".*?)</table>~msi', "$content", $match)) {
                $content = $match[1];
            }
            $content = str_replace('&nbsp;', ' ', $content);
            $content = preg_replace('~<script[^>]*>.*?</script>~msi', ' ', $content);
            // Получаем доп инфу по торренту
            $fields = array();
            if (preg_match_all('~<b>(.*?)</b>:?(.+?)<br( /)?>~msi', $content, $match)) {
                for ($i = 0; $i < count($match[0]); $i++) {
                    $key = mb_strtolower(trim(strip_tags(str_replace(':', '', $match[1][$i]))), 'utf-8');
                    $val = trim(trim(strip_tags($match[2][$i])), ':;');
                    if (!empty($val)) {
                        if (!isset($fields[$key])) {
                            $fields[$key] = array($val);
                        } elseif (!in_array($val, $fields[$key])) {
                            array_push($fields[$key], $val);
                        }
                    }
                }
            }
            // format
            $format = '';
            if (isset($fields['формат'])) {
                $format = implode('<br />', $fields['формат']);
            }
            $entry->setFormat($format);
            // quality
            $quality = '';
            if (isset($fields['качество'])) {
                $quality = implode('<br />', $fields['качество']);
            }
            $entry->setQuality($quality);
            // translate
            $translate = '';
            if (isset($fields['перевод'])) {
                $translate = implode('<br />', $fields['перевод']);
            }
            $entry->setTranslate($translate);
            // video codec
            $video_codec = '';
            if (isset($fields['видео кодек'])) {
                $video_codec = implode('<br />', $fields['видео кодек']);
            } elseif (isset($fields['кодек'])) {
                $video_codec = implode('<br />', $fields['кодек']);
            }
            $entry->setVideoCodec($video_codec);
            // video
            $video = '';
            if (isset($fields['видео'])) {
                $video = implode('<br />', $fields['видео']);
            }
            $entry->setVideo($video);
            // audio codec
            $audio_codec = '';
            if (isset($fields['аудио кодек'])) {
                $audio_codec = implode('<br />', $fields['аудио кодек']);
            }
            $entry->setAudioCodec($audio_codec);
            // audio
            $audio = '';
            if (isset($fields['аудио'])) {
                $audio = implode('<br />', $fields['аудио']);
            } else {
                $audios = array();
                foreach ($fields as $key => $val) {
                    if (false !== mb_strpos($key, 'аудио', null, 'utf-8')) {
                        $audios = array_merge($audios, $val);
                    }
                }
                array_unique($audios);
                $audio = implode('<br />', $audios);
            }
            if (empty($audio)) {
                if (isset($fields['звук'])) {
                    $audio = implode('<br />', $fields['звук']);
                } else {
                    $audios = array();
                    foreach ($fields as $key => $val) {
                        if (false !== mb_strpos($key, 'звук', null, 'utf-8')) {
                            $audios = array_merge($audios, $val);
                        }
                    }
                    array_unique($audios);
                    $audio = implode('<br />', $audios);
                }
            }
            $entry->setAudio($audio);
             
            // videoEntry
            $videoTitle = '';
            $videoOrigTitle = '';
            $videoYear = '';
            $videoLength = '';
            $videoImage = '';
            $videoDescription = '';
            $videoCountries = array();
            $videoGenres = array();
            $videoDirectors = array();
            $videoActors = array();
            // video title
            if (isset($fields['название'])) {
                $videoTitle = current($fields['название']);
            } elseif (isset($fields['название мультфильма'])) {
                $videoTitle = current($fields['название мультфильма']);
            } else {
                if (preg_match('~^(.*?) \(\s*(\d{4})~msi', $entry->getTitle(), $match)) {
                    $videoTitle = trim($match[1]);
                    $videoYear = (int) $match[2];
                    if (preg_match('~^(.*?) / (.*?)$~msi', $videoTitle, $match)) {
                        $videoTitle = trim($match[1]);
                        $videoOrigTitle = trim($match[2]);
                    }
                }
            }
            $videoTitle = trim(preg_replace(array('~\[.*?\]~', '~\(.*?\)~', '~/.*?/~'), '', $videoTitle));
            $entry->videoEntry->setTitle($videoTitle);
            // video orig_title
            if (isset($fields['оригинальное название'])) {
                $videoOrigTitle = current($fields['оригинальное название']);
            }
            $videoOrigTitle = trim(preg_replace(array('~\[.*?\]~', '~\(.*?\)~', '~/.*?/~'), '', $videoOrigTitle));
            if ($videoTitle != $videoOrigTitle) {
                $entry->videoEntry->setOrigTitle($videoOrigTitle);
            }
            // video year
            if (isset($fields['год выхода'])) {
                $videoYear = (int) current($fields['год выхода']);
            } elseif (isset($fields['год выпуска'])) {
                $videoYear = (int) current($fields['год выпуска']);
            }
            $entry->videoEntry->setYear($videoYear);
            // video length
            if (isset($fields['продолжительность'])) {
                $videoLength = current($fields['продолжительность']);
            }
            $entry->videoEntry->setLength($videoLength);
            // video description
            if (isset($fields['описание'])) {
                $videoDescription = current($fields['описание']);
            }
            if (empty($videoDescription) && isset($fields['о фильме'])) {
                $videoDescription = current($fields['о фильме']);
            }
            if (empty($videoDescription) && isset($fields['о мультфильме'])) {
                $videoDescription = current($fields['о мультфильме']);
            }
            $entry->videoEntry->setDescription($videoDescription);
            // video countries
            $value = '';
            if (isset($fields['страна'])) {
                $value = current($fields['страна']);
            } elseif (isset($fields['выпущено'])) {
                $value = current($fields['выпущено']);
            }
            $videoCountries = array_unique(array_filter(array_map('trim', preg_split('~[,/]~', $value))));
            $entry->videoEntry->setCountries($videoCountries);
            // video genres
            if (isset($fields['жанр'])) {
                $value = current($fields['жанр']);
                $videoGenres = array_unique(array_filter(array_map('trim', preg_split('~[,/]~', $value))));
            }
            $entry->videoEntry->setGenres($videoGenres);
            // video directors
            if (isset($fields['режиссер'])) {
                $value = current($fields['режиссер']);
                $videoDirectors = array_unique(array_filter(array_map(array($this, 'handlePerson'), explode(',', $value))));
            }
            $entry->videoEntry->setDirectors($videoDirectors);
            // video actors
            if (isset($fields['в ролях'])) {
                $value = current($fields['в ролях']);
                $videoActors = array_unique(array_filter(array_map(array($this, 'handlePerson'), explode(',', $value))));
            }
            $entry->videoEntry->setActors($videoActors);
            // title
            if (empty($videoTitle)) {
                $videoTitle = '';
                $videoOrigTitle = '';
                if (preg_match('~(.*?) \(\d{4}\)~msi', $entry->getTitle(), $match)) {
                    $videoTitle = trim(strip_tags($match[1]));
                    if (preg_match('~^(.*?) / (.*?)$~msi', $videoTitle, $match)) {
                        $videoTitle = trim($match[1]);
                        $videoOrigTitle = trim($match[2]);
                    }
                }
                if (!empty($videoTitle)) {
                    $videoTitle = trim(preg_replace(array('~\[.*?\]~', '~\(.*?\)~', '~/.*?/~'), '', $videoTitle));
                    $entry->videoEntry->setTitle($videoTitle);
                }
                $videoOrigTitle = trim(preg_replace(array('~\[.*?\]~', '~\(.*?\)~', '~/.*?/~'), '', $videoOrigTitle));
                if (!empty($videoOrigTitle) && $videoOrigTitle != $videoTitle) {
                    $entry->videoEntry->setOrigTitle($videoOrigTitle);
                }
            }
            // video image
            if (preg_match('~<img\s+class="linked-image"\s+src="([^"]+)"~msi', $content, $match)) {
                $videoImage = $match[1];
            }
            $entry->videoEntry->setImage($videoImage);
            
            // screenhots
            if (preg_match_all('~<a\s+href="([^"]+)"\s+class="highslide"[^>]*>\s*<img\s+src="([^"]+)"[^>]*>~msi', $content, $match)) {
                for ($i = 0; $i < count($match[0]); $i++) {
                    $screenshotLink = trim($match[1][$i]);
                    $screenshotImage = trim($match[2][$i]);
                    $entry->addScreenshot($screenshotLink, $screenshotImage);
                }
            }
            
            return $entry;
        }
        return false;
    }
     
    /**
     * Обработка персоны
     * @param string $str
     */
    protected function handlePerson($str) {
        return trim(preg_replace('~/.*$~', '', $str));
    }
     
}
